package com.example.music.ui.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.music.R
import com.example.music.ui.adapters.RecentMusicAdapter

class ProfileFragment : BaseFragment() {
    
    private lateinit var recentMusicAdapter: RecentMusicAdapter
    
    override fun getLayoutRes(): Int = R.layout.fragment_profile
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return super.onCreateView(inflater, container, savedInstanceState)
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecyclerView()
        observeViewModel()
    }
    
    private fun setupRecyclerView() {
        recentMusicAdapter = RecentMusicAdapter { music ->
            viewModel.playMusic(music)
        }
        
        val profileRecentMusicRecyclerView = view?.findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.profileRecentMusicRecyclerView)
        profileRecentMusicRecyclerView?.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            adapter = recentMusicAdapter
        }
    }
    
    private fun observeViewModel() {
        viewModel.musicList.observe(viewLifecycleOwner, Observer { musicList ->
            val profileTotalMusicCount = view?.findViewById<android.widget.TextView>(R.id.profileTotalMusicCount)
            profileTotalMusicCount?.text = musicList.size.toString()
            recentMusicAdapter.updateMusicList(musicList.take(5))
        })
    }
}
